package gotnames.web.st;

import gotnames.Utils;
import gotnames.dm.User;
import gotnames.web.Facebook;

import java.util.Collection;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.medallia.spider.RenderTask;
import com.medallia.tiny.CollUtils;
import com.medallia.tiny.Func;
import com.medallia.tiny.Funcs;

/**
 * Task which allows users to grab a profile picture from their Facebook profile
 * and use it in Got Names. This task first allows users to authenticate via
 * Facebook and then downloads and displays their profile picture, allowing the
 * user to pick one. After that they are sent to {@link FacebookCropPhotoTask}.
 */
public class FacebookProfilePicTask extends RenderTask {
	
	@Output interface Values {
		V<String> APP_ID = v();
		V<Collection<Collection<PhotoWebView>>> PHOTO_ROWS = v();
	}
	
	PostAction action(User user, Facebook fb) throws JSONException {
		if (!fb.isAuthorized()) {
			attr(Values.APP_ID, fb.getAppId());
			return template("facebookAuth");
		}
		
		JSONObject album = findProfileAlbum(fb);
		if (album == null)
			return rawStringUtf8("No profile album found");
		
		final JSONArray photos = fb.query(album.getString("id") + "/photos").getJSONArray("data");
		
		attr(Values.PHOTO_ROWS, CollUtils.split(Funcs.map(Utils.range(photos.length()), new Func<Integer, PhotoWebView>() {
			@Override public PhotoWebView call(Integer photoIdx) {
				final JSONObject photo;
				try {
					photo = photos.getJSONObject(photoIdx);
				} catch (JSONException e) {
					throw new IllegalArgumentException(e);
				}
				return new PhotoWebView() {
					@Override public String getId() {
						return getString(photo, "id");
					}
					@Override public String getUrl() {
						return getString(photo, "picture");
					}
					private String getString(JSONObject obj, String field) {
						try {
							return obj.getString(field);
						} catch (JSONException e) {
							throw new IllegalArgumentException("for " + field, e);
						}
					}
				};
			}
		}), 4));
		return null;
	}
	
	private JSONObject findProfileAlbum(Facebook fb) throws JSONException {
		JSONArray albums = fb.query("me/albums").getJSONArray("data");
		for (int i = 0; i < albums.length(); i++) {
			JSONObject album = albums.getJSONObject(i);
			String type = album.getString("type");
			if ("profile".equals(type))
				return album;
		}
		return null;
	}

	public interface PhotoWebView {
		String getId();
		String getUrl();
	}

	@Override public String getPageTitle() { return "Facebook Profile Picture"; }

}
